<?php

namespace App\Http\Controllers\Api\SmallApp\User;

use App\Http\Controllers\Common\ApiController;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class LoginController extends ApiController {

    public function loginWithVerifyCode(Request $request) {

        $phone = $request->input('phone');
        $verify_code = $request->input('verify_code');

        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|Integer',
        ]);

        if(env('APP_ENV')!='local'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $user = User::where(compact('phone'))->first();
        if(empty($user))
            return responseFail('未查到有效用户，请先注册！');

        $user->token = createNewToken($user->id);
        //$user->public_openid = $user->wx_public_open_id;
        return responseSuccess($user->toArray());


    }

    public function loginWithPassword(Request $request) {

        //Log::info('loginWithPassword');
        $phone = $request->input('phone');
        $password = $request->input('password');

        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'password'=>'required',
        ]);
        $password = md5($password);
        $user = User::where(compact('phone','password'))->first();
        if(empty($user))
            return responseFail('用户名或密码错误！');

        $user->token = createNewToken($user->id);
        //$user->public_openid = $user->wx_public_open_id;
        return responseSuccess($user->toArray());


    }

}
